package com.goods.business.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goods.business.mapper.ProductMapper;
import com.goods.business.mapper.ProductStockMapper;
import com.goods.business.service.ProductService;
import com.goods.common.error.BusinessCodeEnum;
import com.goods.common.error.BusinessException;
import com.goods.common.model.business.Product;
import com.goods.common.model.business.ProductStock;
import com.goods.common.vo.business.ProductStockVO;
import com.goods.common.vo.business.ProductVO;
import com.goods.common.vo.system.PageVO;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: Mr.Cao
 * @DateTime: 2021/11/9 18:42
 * BMW F750GS
 **/
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    /**
     * 分页 获取全部的物资信息
     */
    @Override
    public PageVO findProductList(Map queryMap) {
        //条件查询
        Example o = new Example(Product.class);
        Example.Criteria criteria = o.createCriteria();
        //匹配name
        String name = (String) queryMap.get("name");
        if (!StringUtils.isEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        //匹配status
        String status = (String) queryMap.get("status");
        if (!StringUtils.isEmpty(status)){
            criteria.andEqualTo("status",status);
        }else {
            criteria.andEqualTo("status",0);
        }
        //匹配三级分类: 目前业务只支持三级分类查询
        String categoryId = (String) queryMap.get("categorys");
        if (!StringUtils.isEmpty(categoryId)) {
            String[] split = categoryId.split(",");
            String threeCategoryId = split[2];//三级分类ID
            if (!StringUtils.isEmpty(threeCategoryId)) {
                criteria.andEqualTo("threeCategoryId", threeCategoryId);
            }
        }
        //分页
        String pageNum = (String) queryMap.get("pageNum");
        String  pageSize = (String) queryMap.get("pageSize");
        //通过PageHelper实现分页：每页显示5条记录
        Page<Object> page = PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        //查询
        List<Product> products = productMapper.selectByExample(o);
        //转Vo
        ArrayList<ProductVO> productVOS = new ArrayList<>();
        for (Product product : products) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product,productVO);
            productVOS.add(productVO);
        }
        return new PageVO(page.getTotal(),productVOS);
    }
    /**
     * 物资审核通过
     * */
    @Override
    public void publish(long id) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        if (product!=null){
            product.setStatus(0);//设置物资状态正常
            productMapper.updateByPrimaryKey(product); //更新数据
        }
    }
    /**
     * 物资恢复 回收站中恢复
     * */
    @Override
    public void back(long id) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        if (product!=null){
            product.setStatus(0);//设置物资状态正常
            productMapper.updateByPrimaryKey(product); //更新数据
        }
    }
    /**
     * 删除回收站的物资
     * */
    @Override
    public void delete(long id) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        if (product!=null){
            productMapper.delete(product); //删除
        }
    }
    /**
     * 移除物资到回收站
     * */
    @Override
    public void remove(long id) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        if (product!=null){
            product.setStatus(1);//设置物资状态为 回收
            productMapper.updateByPrimaryKey(product); //更新
        }
    }
    /**
     * 添加物资信息
     * */
    @Override
    public void add(ProductVO productVO) {
        if (productVO!=null){
            @NotNull(message = "分类不能为空") Long[] categoryKeys = productVO.getCategoryKeys();
            Product product = new Product();
            BeanUtils.copyProperties(productVO,product);
            //封装一二三级分类Id
            product.setOneCategoryId(categoryKeys[0]);
            product.setTwoCategoryId(categoryKeys[1]);
            product.setThreeCategoryId(categoryKeys[2]);
            //封装创建时间和更新时间
            product.setCreateTime(new Date());
            product.setModifiedTime(new Date());
            //生成商品编号
            product.setPNum(UUID.randomUUID().toString());
            //设置状态为待审核
            product.setStatus(2);
            productMapper.insert(product);
        }
    }
    /**
     * 编辑物资资料是数据回显
     * */
    @Override
    public ProductVO edit(long id) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        //转Vo
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product,productVO);
        return productVO;
    }
    /**
     * 更新物资资料
     * */
    @Override
    public void update(long id,ProductVO productVO) {
        //查询
        Product product = productMapper.selectByPrimaryKey(id);
        if (product!=null){
            BeanUtils.copyProperties(productVO,product);
            product.setModifiedTime(new Date());//设置更新时间
            productMapper.updateByPrimaryKey(product);
        }
    }
    /**
     * 查询物资库存
     * */
    @Override
    public PageVO findProductStocks(Map queryMap) throws BusinessException {
        //分页
        String pageNum = (String) queryMap.get("pageNum");
        String  pageSize = (String) queryMap.get("pageSize");
        //通过PageHelper实现分页：每页显示5条记录
        Page<Object> page = PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        //条件查询 查询商品信息
        Example o = new Example(Product.class);
        Example.Criteria criteria = o.createCriteria();
        //三级分类Id
        String  categorys = (String) queryMap.get("categorys");
        if (!StringUtils.isEmpty(categorys)){
            String[] split = categorys.split(",");
            if (split.length<3){
                throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"目前支持三级分类查询");
            }
            criteria.andEqualTo("threeCategoryId",split[2]);
        }
        //物资名称
        String  name = (String) queryMap.get("name");
        if (!StringUtils.isEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        //状态为 为正常 :0
        criteria.andEqualTo("status",0);
        //查询
        List<Product> products = productMapper.selectByExample(o);
        //转换Vo
        List<ProductStockVO> productStockVOList = products.stream().map(product -> {
            ProductStockVO productStockVO = new ProductStockVO();
            BeanUtils.copyProperties(product, productStockVO);
            //查询库存
            Example exampleProductStock = new Example(ProductStock.class);
            exampleProductStock.createCriteria().andEqualTo("pNum", product.getPNum());
            ProductStock productStock = productStockMapper.selectOneByExample(exampleProductStock);
            if (productStock!=null) {
                productStockVO.setStock(productStock.getStock());
            }else {
                productStockVO.setStock(0L);
            }
            return productStockVO;
        }).collect(Collectors.toList());
        return new PageVO(page.getTotal(),productStockVOList);
    }

}
